package easy;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Stack;
import java.util.stream.Collectors;

public class Solution_145 {

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
//        digui(root, list);

        TreeNode pre = null;
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.empty() || root!=null) {
            if (root == null) {
                // 返回上一个节点
                root = stack.pop(); // 取出null的父节点
                if (root.right == null || root.right == pre) {
                    // 从右节点退回来的
                    list.add(root.val);
                    pre = root;
                    root = null;
                } else {
                    // 从左节点退回来的
                    stack.add(root);
                    pre = null;
                    root = root.right;
                }
            } else {
                stack.add(root);
                root = root.left;
            }
        }
        return list;
    }

    public void digui(TreeNode node, List<Integer> list) {
        if (node == null) {
            return;
        } else {
            digui(node.left, list);
            digui(node.right, list);
            list.add(node.val);
        }
    }

    public static void main(String[] args) {
        Solution_145 main = new Solution_145();
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(3);
//        root.right = new TreeNode(2);
        root.left.left = new TreeNode(1);
        List<Integer> list = main.inorderTraversal(root);
        for (Integer integer : list) {
            System.out.print(integer+",");
        }
        System.out.println();
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}